import { Sort } from "../public/Sort"
import { DefaultCompare, ICompareFunction, CompareEnum } from "../public/Utils"

/**
 * 选择排序
 * 找到最小值并将其放置在第一位，接着找到第二小的值将其放在第二位，依次类推。
 * **/
 export class SelectSort<T> extends Sort<T> {
    constructor(array: Array<T> = [], compareFun: ICompareFunction = new DefaultCompare()) {
        super(array, compareFun)
    }
    sort(): void {
        //获取数组长度
        const { length } = this.array
        // 声明一个变量用于存储最小元素的位置
        let indexMin: number
        for (let i: number = 0; i < length; i++) {
            //初始值为外层循环当前遍历到的位置i
            indexMin = i
            for (let j: number = i; j < length; j++) {
                //如果当前遍历到的元素小于indexMin位置的元素,就将当前遍历到的位置j赋值给indexMin
                if (this.compare.compare(this.array[i], this.array[j]) === CompareEnum.BIGGER) {
                    indexMin = j
                }
            }
            //找到更小的值则交换位置
            i !== indexMin && this.swap(this.array, i, indexMin)
        }
    }
}

const SelectSortTest = (): void => {
    const array = [321, 544, 547, 1215,554]
    const selectSort:  Sort<Number> = new SelectSort<Number>(array)
    selectSort.sort()
    console.log(array);
}
SelectSortTest()